package com.ruowei.modules.foodOrder.service;

import com.ruowei.modules.foodOrder.domain.OrderLifeCycle;
import com.ruowei.modules.foodOrder.repository.OrderLifeCycleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;

@Service
@Slf4j
public class LifeCycleService {

    private final OrderLifeCycleRepository lifeCycleRepository;

    public LifeCycleService(OrderLifeCycleRepository lifeCycleRepository) {
        this.lifeCycleRepository = lifeCycleRepository;
    }

    public void saveLifeCycle(String orderCode, String orderReturnCode, String title, String description) {
        saveLifeCycle(orderCode, orderReturnCode, title, description, true);
    }

    public void saveLifeCycle(String orderCode, String orderReturnCode, String title, String description, boolean repeatable) {
        if (repeatable) {
            OrderLifeCycle lifeCycle = new OrderLifeCycle();
            lifeCycle.setOrderCode(orderCode);
            lifeCycle.setOrderRerunCode(orderReturnCode);
            lifeCycle.setTitle(title);
            lifeCycle.setTime(Instant.now());
            lifeCycle.setDescription(description);
            lifeCycleRepository.saveAndFlush(lifeCycle);
        } else {
            if (!lifeCycleRepository.findFirstByOrderCodeAndTitleOrderByTimeAsc(orderCode, title).isPresent()) {
                OrderLifeCycle lifeCycle = new OrderLifeCycle();
                lifeCycle.setOrderCode(orderCode);
                lifeCycle.setOrderRerunCode(orderReturnCode);
                lifeCycle.setTitle(title);
                lifeCycle.setTime(Instant.now());
                lifeCycle.setDescription(description);
                lifeCycleRepository.saveAndFlush(lifeCycle);
            }
        }
    }
}
